from ui.NewUi import MainWindow
import pandas as pd
from ttkbootstrap.constants import *
from tkinter import messagebox, ttk, IntVar, StringVar
from ttkbootstrap import Progressbar
import tkinter as tk
import openpyxl
from core import Core
import os
import sys
import subprocess
import time


class MyProgram(MainWindow):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.file = None
        self.df = pd.DataFrame({})
        self.core = None

    # 点击分析按钮，以下函数开始执行
    def calculate(self):
        if os.path.exists(self.file_name.get()):
            self.core = Core(self.file_name.get(), self.ana)  # 以上参数都是由界面传递过来的
            if self.core.check:
                self.generate_file()
        else:
            messagebox.showerror('文件错误！', '文件未选择或者文件路径不存在！')

    def generate_file(self):
        p_window = tk.Toplevel(root)
        px, py = center(self.master, 300, 100)
        p_window.geometry(f"300x100+{px}+{py}")
        p_window.title("正在生成...")
        p_window.grab_set()
        bar_value = IntVar(value=0)
        bar_str = StringVar(value="0%")

        progress = ttk.Progressbar(p_window, length=200, mode='determinate', variable=bar_value)
        progress.pack(side='top', fill=X, expand=False, padx=20, pady=20)

        p_label = tk.Label(p_window, textvariable=bar_str, anchor=CENTER)
        p_label.pack(side='top', fill=X, pady=0)
        progress["maximum"] = 100
        # progress["value"] = 0
        try:
            writer = pd.ExcelWriter("result.xlsx")
            basic_data = self.core.basic_data()
            if '考号' in basic_data.columns:
                basic_data['考号'] = basic_data['考号'].apply(str)
            basic_data.to_excel(writer, sheet_name='成绩数据')
            bar_value.set(value=20)
            bar_str.set("20%")
            self.core.distribution().to_excel(writer, sheet_name='成绩分布')
            # progress['value'] = 40
            bar_value.set(value=40)
            bar_str.set("40%")
            self.core.summarize_grade().to_excel(writer, sheet_name='年级总体')
            # progress['value'] = 60
            bar_value.set(value=60)
            bar_str.set("60%")
            self.core.summarize_class().to_excel(writer, sheet_name='班级分析')
            bar_value.set(value=100)
            bar_str.set("100%")
            writer.close()
            if sys.platform.startswith('darwin'):
                subprocess.call(["open", 'result.xlsx'])
            else:
                os.startfile('result.xlsx')

        except PermissionError:
            messagebox.showerror('错误!', '导出无法继续，请关闭result.xlsx文件！')
        except OSError:
            messagebox.showerror("打开错误！", "文件无法打开，请重新生成！")
        finally:
            p_window.destroy()


# 让窗口居中显示
def center(r, w, h):
    sw = r.winfo_screenwidth()
    # 得到屏幕宽度
    sh = r.winfo_screenheight()
    wx = (sw - w) / 2
    wy = (sh - h) / 2
    return int(wx), int(wy)


if __name__ == '__main__':
    # root = ttk.Window('七彩成绩分析工具v2.0版')
    root = tk.Tk()
    root.title("七彩成绩分析工具v2.0版")
    # sw = root.winfo_screenwidth()
    # # 得到屏幕宽度
    # sh = root.winfo_screenheight()
    # # 得到屏幕高度
    ww = 950
    wh = 650
    # x = (sw - ww) / 2
    # y = (sh - wh) / 2
    x, y = center(root, ww, wh)
    root.geometry("%dx%d+%d+%d" % (ww, wh, x, y))
    MyProgram(root).pack(fill=BOTH, expand=YES)
    root.mainloop()
